###############################
#   gmaps.py
###############################
import logging
import urllib
from google.appengine.api import urlfetch

from time import sleep

key = "ABQIAAAAv55cC37g-7Kq0tZb3OOnqRQnU_v54FpdkJS74BFyZRh0JCiBYxRtg6R36hcIWTrfmsCUAcOVcGYo6g"

def location2latlong( query, key=key ):
    """Get the ( latitute, longitude ) coordinates corresponding
    to the query. If something goes wrong return None."""

    output = 'csv'

    params = { }
    params[ 'key' ] = key
    params[ 'output' ] = output
    params[ 'q' ] = query

    params = urllib.urlencode( params )
    
    logging.debug( "Geocode parameters: %s" % params )

    try:
        f = urlfetch.fetch( "http://maps.google.com/maps/geo?%s" % params )
    except IOError:
        # maybe some local problem at google? let's try again
        sleep( 2 )
        try:
            f = urlfetch.fetch( "http://maps.google.com/maps/geo?%s" % params )
        except IOError:
            # okay we give up
            return None
         
    response = f.content.split(',')

    try:
        status = response[0]
        accuracy = response[1]
        latitude = response[2]
        longitude = response[3]
    except:
        return None

    if status != '200':
        return None
    else:
        return latitude, longitude

if __name__ == '__main__':
    import sys

    try:
        q = sys.argv[1]
    except:
        print 'Usage: python gmaps.py query'
        sys.exit( 1 )

    r = location2latlong( q )
    if r is not None:
        print r
    else:
        print 'Something went wrong.'

